<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 登录 Model
 *
 * @author      Eden
 * @datetime    2016/11/26 15:43
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Login_Model extends ADM_Model
{

    // 用户信息
    private $adminDetail = array();

    // 角色信息
    private $roleDetail = array();

    private $baseId = 0;

    /**
     * 继承你构造器类
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function getBaseID() {
        return $this->baseId;
    }

    public function checkAdmin($email, $password)
    {
        $query = $this->db->get_where('admin', array('email' => $email));
        if (empty($query)) {
            $this->setError('用户不存在');
            return false;
        }

        $result = $query->row_array();
        if ($result['password'] === md5($password . $result['salt'])) {
            $adminId = $result['id'];
            // 获取 Profile 信息
            $profileQuery = $this->db->get_where('admin_profile', array('adminId' => $adminId));
            $profile = $profileQuery->row_array();
            $this->adminDetail = array_merge($result, $profile);

            // 获取 Role 信息
            $roleQuery = $this->db->get_where('admin_role', array('id' => $result['roleId']));
            $this->roleDetail = $roleQuery->row_array();

            $this->baseId = $result['baseId'];

            // 更新最后登录信息
            $this->db->update(
                'admin',
                array('lastIP' => remoteAddr(), 'lastTime' => date('Y-m-d H:i:s')),
                array('id' => $result['id'])
            );
            return true;
        } else {
            $this->setError('用户名或密码错误');
            return false;
        }
    }

    /**
     * 获取用户信息
     * @return mixed
     */
    public function getDetail()
    {
        $detail = array(
            'adminId' => (int) value($this->adminDetail, 'id'),
            'baseId' => intval(value($this->adminDetail, 'baseId')),
            'roleId' => (int) value($this->adminDetail, 'roleId'),
            'role' => value($this->roleDetail, 'role'),
            'email' => value($this->adminDetail, 'email'),
            'nickName' => value($this->adminDetail, 'nickName'),
            'trueName' => value($this->adminDetail, 'trueName'),
            'created' => value($this->adminDetail, 'created'),
            'lastTime' => value($this->adminDetail, 'lastTime'),
            'lastIP' => value($this->adminDetail, 'lastIP'),
            'avatar' => thumb($this->adminDetail['avatar'], 100, 100)
        );

        return $detail;
    }

}
